<template>
  <view>
    请选择头像
    <!-- @chooseavatar获取用户头像回调,需要与methods中onChooseAvatar(e)相配合 -->
    <button class="nickName" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
      <image class="avatarImg" :src="avatarUrl"></image>
    </button>
    <input style="height: 20vw;" type="nickname" v-model="nickName" placeholder="请输入昵称" />
    <view> <button @click="login()">微信一键登陆</button> </view>
    <u-loading-icon v-if="loading" text="登陆中..." textSize="18"></u-loading-icon>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        loading: false,
        'avatarUrl': '',
        'nickName': '',
        show: false
      }
    },
    methods: {
      login() {
        this.loading = true;
        let ava = this.avatarUrl;
        let nik = this.nickName;

				let that = this;
				uni.login({
					"provider": "weixin",
					"onlyAuthorize": true, // 微信登录仅请求授权认证
					success: function(event) {
						const {
							code
						} = event
						//客户端成功获取授权临时票据（code）,向业务服务器发起登录请求。
						console.log(event.code)
						uni.request({
							url: 'http://127.0.0.1:800/mhs/user/loginByWeixin', //后端登陆接口
							data: {
								code: event.code,
								avatarUrl: ava,
								nickName: nik
							},
							success: (res) => {
								if (res.data.code == 1) {
									//获得token完成登录,并将token存入本地缓存
									uni.setStorageSync('token', res.data.data.token);
									that.$websocket.state.token =  res.data.data.token;
									//存入user
									uni.setStorageSync('loginUser', res.data.data.loginUser.id);
									//连接websocket服务并存入
									that.$websocket.commit('webSocketInit', res.data.data.loginUser.id);
									that.$websocket.commit('setUid',res.data.data.loginUser.id);
									//获取token的方法,其他页面可以通过这种方式获取token
									// let token = uni.getStorageSync('token');
									// console.log(res.data.msg);
									//弹出用户提示框,跳转到user页
									that.loading = false;
									uni.showToast({
										title: '登陆成功',
										duration: 2000,
										mask: true //是否有透明蒙层，默认为false
									})
									//跳转到user页
									uni.reLaunch({
										url: '../user/user'
									});
								}
							}
						});
					},
					fail: function(err) {
						this.loading = false;
						uni.showToast({
							title: '登陆失败',
							duration: 2000,
							mask: true //是否有透明蒙层，默认为false
						})
						// 登录授权失败
						// err.code是错误码
					}
				})
			},
			onChooseAvatar(e) {
				let that = this;
				const {
					avatarUrl
				} = e.detail
				// this.avatarUrl = e.detail
				that.setData({
					avatarUrl,
				})
			}

    }
  }
</script>

<style>
  .nickName {
    width: 50vw;
    height: 50vw;
  }

  .avatarImg {
    width: 100%;
    height: 100%;
  }
</style>